package com.org.cys.controller.system;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.org.cys.controller.base.BaseController;
import com.org.cys.pojo.base.Const;
import com.org.cys.pojo.system.data.PrivilegeEnum;
import com.org.cys.service.system.PrivilegeRoleService;
import com.org.cys.service.system.PrivilegeService;
import com.org.cys.service.system.RoleService;
import com.org.cys.service.system.UserRoleService;
import com.org.cys.service.system.UserService;
import com.org.cys.util.MD5;
import com.org.cys.util.MapUtil;
import com.org.cys.util.PageData;
import com.org.cys.util.StringUtil;  
  

/**
 * 后台首页Controller
 * @author caiyushen
 * */
@Controller  
@RequestMapping("/admin")  
public class AdminController extends BaseController{  
    
	private static Logger logger = Logger.getLogger(AdminController.class);
	
	@Resource(name="userServiceImpl")
    private UserService userService;  
     
	@Resource(name="roleServiceImpl")
	private RoleService roleService;
    
	@Resource(name="userRoleServiceImpl")
	private UserRoleService userRoleService;
	
	@Resource(name="privilegeServiceImpl")
	private PrivilegeService privilegeService;
	
	@Resource(name="privilegeRoleServiceImpl")
	private PrivilegeRoleService privilegeRoleService;
	
	/**
	 * 跳转到后台主页面
	 * */
	@RequestMapping(value="/toIndex",method = RequestMethod.GET)  
    public String toIndex(Model model) throws Exception{  
		//shiro管理的session
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		PageData user = (PageData)session.getAttribute(Const.sessionUser);
		model.addAttribute("user",user);
        return "admin/index";  
    }  
	
	/**
	 * 跳转到后台主页面
	 * */
	@RequestMapping(value="/toMain",method = RequestMethod.GET)  
    public String toMain() throws Exception{  
        return "admin/main";  
    }  
	
	/**
	 * 获取菜单树
	 * @throws Exception 
	 * */
	@ResponseBody
    @RequestMapping(value="/getMenu",method = RequestMethod.GET)
    public PageData getMenu() throws Exception{
    	logger.info("method getMenu()");
    	PageData result = new PageData();
    	//shiro管理的session
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		Long userId = (Long)session.getAttribute(Const.sessionUserId);
    	List<PageData> userRoleList = userRoleService.getListByUserId(userId);
    	if(StringUtil.checkObj(userRoleList)&&userRoleList.size()>0){
    		PageData userRole = userRoleList.get(0);
    		Long roleId = MapUtil.getLong(userRole, "roleId");
    		if(StringUtil.checkObj(roleId)){
            	try {
            		//获取权限树
        			List<PageData> privilegeMidList = privilegeRoleService.getPrivilegeListByRoleIdAndType(roleId,PrivilegeEnum.PrivilegeType.meun.getIndex());
        			if(StringUtil.checkObj(privilegeMidList)){
        				List<PageData> treeList = new ArrayList<>();
        				for(PageData parent:privilegeMidList){
        					Long parentId = MapUtil.getLong(parent, "privilegeParentId");
        					//获取一级父级权限
        					if(!StringUtil.checkObj(parentId)){
        						parentId = MapUtil.getLong(parent, "privilegeId");
        						//名称
        						parent.put("text", MapUtil.getString(parent, "privilegeName"));
        						List<PageData> childrenList = new ArrayList<>();
        						for(PageData children : privilegeMidList){
        							Long childrenParentId = MapUtil.getLong(children, "privilegeParentId");
        							if(StringUtil.checkObj(childrenParentId) && childrenParentId.equals(parentId)){
        								children.put("text", MapUtil.getString(children, "privilegeName"));
        								childrenList.add(children);
        							}
        						}
        						parent.put("children", childrenList);
        						treeList.add(parent);
        					}
        				}
        				result.put("treeList", treeList);
        			}
        		} catch (Exception e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		} 
    		}
    	}
    	logger.info("method getMenu() result: "+ result.toString());
    	return result;
    }
	
	
	
	/**
	 * 用户重设密码
	 * @param oldPassword 旧密码
	 * @param newPassword 新密码
	 * @param repeatPassword 重复密码
	 * @author caiyushen
	 * @throws Exception 
	 * */
	@ResponseBody
    @RequestMapping(value="/updatePassword",method = RequestMethod.POST)
	public PageData updatePassword(@RequestParam String oldPassword,@RequestParam String newPassword,@RequestParam String repeatPassword) throws Exception{
		logger.info("method updatePassword() oldPassword:"+oldPassword+" newPassword:"+newPassword+" repeatPassword:"+repeatPassword);
    	PageData result = new PageData();
    	result.put("success", false);
    	if(StringUtil.checkObj(oldPassword) && StringUtil.checkObj(newPassword) &&  StringUtil.checkObj(repeatPassword)){
    		if(newPassword.equals(repeatPassword)){
    	    	//shiro管理的session
    			Subject currentUser = SecurityUtils.getSubject();  
    			Session session = currentUser.getSession();
    			Long userId = (Long)session.getAttribute(Const.sessionUserId);
        		PageData user = userService.getEntityById(userId);
        		if(StringUtil.checkObj(user)){
        			String userOldPassword = MapUtil.getString(user, "userPassword");
        			oldPassword = MD5.convertPassword(MapUtil.getString(user,"userAccount"), oldPassword);
        			if(userOldPassword.equals(oldPassword)){
        				//修改密码
        				userService.updatePassword(userId,MD5.convertPassword(MapUtil.getString(user,"userAccount"), newPassword));
        				result.put("success", true);
        				return result;
        			}else{
        				result.put("error", "操作失败：旧密码输入错误！");
                    	return result;
        			}
        		}else{
        			result.put("error", "操作失败：用户无效数据！");
                	return result;
        		}
        	}else{
        		result.put("error", "新密码与重复密码不一致！");
            	return result;
        	}
    	}
    	result.put("error", "必填项不能为空！");
    	return result;
	}
}  